# -*- coding: utf-8 -*-
import uuid

import os
import requests
from PIL import Image
from svmutil import *

from utils.utils import huidu_JZ, _9_gg_JZ, remove_border, image_crop, print_image

mapper = {
    "101.0": "A",
    "102.0": "B",
    "103.0": "C",
    "104.0": "D",
    "105.0": "E",
    "106.0": "F",
    "107.0": "G",
    "108.0": "H",
    "109.0": "I",
    "1010.0": "J",
    "1011.0": "K",
    "1012.0": "L",
    "1013.0": "M",
    "1014.0": "N",
    "1015.0": "O",
    "1016.0": "P",
    "1017.0": "Q",
    "1018.0": "R",
    "1019.0": "S",
    "1020.0": "T",
    "1021.0": "U",
    "1022.0": "V",
    "1023.0": "W",
    "1024.0": "X",
    "1025.0": "Y",
    "1026.0": "Z",
    "0.0": "0",
    "1.0": "1",
    "2.0": "2",
    "3.0": "3",
    "4.0": "4",
    "5.0": "5",
    "6.0": "6",
    "7.0": "7",
    "8.0": "8",
    "9.0": "9",
}


def load_new_image():
    """
    下载新的图片
    :return:
    """
    for i in range(500):
        # 下载新图片
        response = requests.get(
            url="http://bm.e21cn.com/func/checkcode.ashx"
        )
        file_path = "../image/test.png"
        with open(file_path, "wb") as img_file:
            img_file.write(response.content)

        # 灰度降噪
        image = Image.open(file_path)
        image = huidu_JZ(image, 200)

        # 9宫格降噪
        image = _9_gg_JZ(image, 1)
        # print_image(image)

        # 去边框
        image = remove_border(image)
        # print_image(image)

        # 字符提取
        image_list = image_crop(image, 6)
        for child_image in image_list:
            child_image.save("../image/biao_zhu/{name}.jpeg".format(name=uuid.uuid4()))
        print("=====>> {0}".format(i))


if __name__ == "__main__":
    """仅仅是为了测试识别效果"""
    # just fot test
    if os.path.exists("test.png"):
        os.remove("test.png")
    if os.path.exists("test_file"):
        os.remove("test_file")

    # 下载新图片
    response = requests.get(
        url="http://bm.e21cn.com/func/checkcode.ashx"
    )
    file_path = "test.png"
    with open(file_path, "wb") as img_file:
        img_file.write(response.content)

    # 灰度降噪、图片2值化
    image = Image.open(file_path)
    image = huidu_JZ(image, 200)
    # print_image(image)

    # 9宫格降噪
    image = _9_gg_JZ(image, 1)
    # print_image(image)

    # 去边框
    image = remove_border(image)
    # print_image(image)

    # 字符提取
    image_list = image_crop(image, 6)

    with open("test_file", "a") as test_file:
        for i in range(len(image_list)):
            child_image = image_list[i]

            image = Image.open(file_path)
            width = child_image.width
            height = child_image.height

            svm_result = str(i) + " "
            # 记录y
            for y in range(11):  # 此处11是图片最大宽高
                count = 0
                if y >= height:
                    svm_result += "{0}:{1} ".format(y + 1, count)
                    continue
                for x in range(11):
                    if x >= width:
                        continue
                    pixel = child_image.getpixel((x, y))
                    if pixel == 0:
                        count += 1
                svm_result += "{0}:{1} ".format(y + 1, count)

            # 记录x
            for x in range(11):
                count = 0
                if x >= width:
                    svm_result += "{0}:{1} ".format(x + 12, count)
                    continue
                for y in range(11):
                    if y >= height:
                        continue
                    pixel = child_image.getpixel((x, y))
                    if pixel == 0:
                        count += 1
                svm_result += "{0}:{1} ".format(x + 12, count)

            test_file.write(svm_result.strip() + "\n")
    # 开始识别
    yt, xt = svm_read_problem("test_file")
    model = svm_load_model("model")
    p_label, p_acc, p_val = svm_predict(yt, xt, model)
    for result in p_label:
        print(mapper[str(result)], end="")
